<html id='dom'>
	<head>
		<link rel='icon' type='image/ico' href='../stylesheets/images/favicon.ico' >
		<title>Welcome to Webble | Login</title>
		<meta name="author" content="Simone D'Avico">
		<link rel="stylesheet" href="../stylesheets/login.css" media="Screen">
		<script>
			console.log(location)
			/***
			 * Initial browser recognition (as the IDE does not work in Firefox, it will prevent from showing login page and show
			 * 	an error page instead)
			 */
			var headers = navigator.userAgent.split(' ')
			for(var i = 0; i < headers.length; i++) {
				if(headers[i].indexOf('Firefox') != -1) {
					//console.log('firefox!')
					var xmlhttp = new XMLHttpRequest();
					xmlhttp.open("GET", location.href +'sorry', true);
					xmlhttp.onload = function() {
						if(xmlhttp.readyState == 4) {
							document.getElementById('dom').innerHTML = xmlhttp.response;
						}
					}
					xmlhttp.send(null);
				}
			}
		</script>
		<script type="text/javascript" src="../libraries/jquery-1.6.2.min.js"></script>
		<script type="text/javascript" src="../libraries/jquery-ui-1.8.16.custom.min.js"></script>
		<script type="text/javascript" src="../libraries/CodeMirror-2.18/lib/codemirror.js"></script>
		<script type="text/javascript" src="../libraries/CodeMirror-2.18/lib/util/foldcode.js"></script>
		<script type="text/javascript" src="../libraries/CodeMirror-2.18/mode/javascript/javascript.js"></script>
		<script type="text/javascript" src="../libraries/CodeMirror-2.18/lib/util/runmode.js"></script>
		<script type="text/javascript" src="../libraries/jquery.treeview/jquery.treeview.js"></script>
		
		
		
		<script>
		
			function getAllUsers() {
				var usersOnDb = [];
				var xmlhttp3 = new XMLHttpRequest()
				xmlhttp3.open('GET', location.href +'user/name/all', false)
				xmlhttp3.send(null)
				if(xmlhttp3.status == 200) { return JSON.parse(xmlhttp3.response).usernames }
			}

			var remember = false;

			//checks if the cookie exists, and if it does, performs the login
			if(document.cookie) {
				console.log('cookie found')
				loginWithCookie()
			}

			/***
			 *  User login
			 */
			function login() {
				var username = document.getElementById('username').value;
				var password = document.getElementById('password').value;
				var errormsg = document.getElementById('errormsg');
				var okmsg = document.getElementById('okmsg');

				if(!(username && password)) {
					return;
				}

				var xmlhttp = new XMLHttpRequest();
				xmlhttp.open("GET", location.href +'user/?name=' + username + '&pw=' + password, true);
				xmlhttp.onload = function() {
					if(xmlhttp.readyState == 4) {
						var res = JSON.parse(xmlhttp.response);
						if(res.user === undefined) {
							errormsg.innerHTML = 'Wrong username/password.';
							errormsg.style.opacity = '1';
							var t = setInterval(function() {
								errormsg.style.opacity = errormsg.style.opacity - 0.1
							}, 200);
							setTimeout(function() {clearInterval(t);
								errormsg.style.opacity = '0'
							}, 2000)
						} else {
							var id = res.id;
							var user = res.user;
							if(password === user.password) {
								var xmlhttp2 = new XMLHttpRequest()
								xmlhttp2.open('GET', location.href +'CodeBubble/?id=' + id)
								xmlhttp2.onload = function() {
									if(xmlhttp2.readyState == 4) {
										document.getElementById('dom').innerHTML = xmlhttp2.response;
										//get IDE page
										eval(document.getElementById('bootScript').innerHTML)//load libraries
										theUser = username; //globale variable for user identification
										//usersOnDb = getAllUsers()
										//set the user
										eval(document.getElementById('identify').innerHTML)// just to put the username on the page
										if(remember && !document.cookie) { setCookie(username, password, 3)
										}
									}
								}
								xmlhttp2.send();
							} else {
								errormsg.innerHTML = 'Wrong username/password.';
								errormsg.style.opacity = '1';
								var t = setInterval(function() {
									errormsg.style.opacity = errormsg.style.opacity - 0.1
								}, 200);
								setTimeout(function() {clearInterval(t);
									errormsg.style.opacity = '0'
								}, 2000)
							}
						}
					}
				}
				xmlhttp.send(null);
			}

			/***
			 * User registration
			 */

			function register() {
				var username = document.getElementById('regusername').value;
				var password = document.getElementById('regpassword').value;
				var errormsg = document.getElementById('errormsg');
				var okmsg = document.getElementById('okmsg');

				if(username === "") {
					errormsg.innerHTML = 'Please enter a username to register.';
					errormsg.style.opacity = '1';
					var t = setInterval(function() {
						errormsg.style.opacity = errormsg.style.opacity - 0.1
					}, 200);
					setTimeout(function() {clearInterval(t);
						errormsg.style.opacity = '0'
					}, 2000)
					return;
				}
				if(password === "") {
					errormsg.innerHTML = 'Please enter a password to register.';
					errormsg.style.opacity = '1';
					var t = setInterval(function() {
						errormsg.style.opacity = errormsg.style.opacity - 0.1
					}, 200);
					setTimeout(function() {clearInterval(t);
						errormsg.style.opacity = '0'
					}, 2000)
					return;
				}

				var xmlhttp = new XMLHttpRequest();
				xmlhttp.open("POST", location.href +'user/new/?name=' + username + '&pw=' + password, true);
				xmlhttp.onload = function() {
					if(xmlhttp.readyState == 3) {
					}
					if(xmlhttp.readyState == 4) {
						var response = xmlhttp.response;
						if(response === "User already exists in the database!") {
							errormsg.innerHTML = 'Username already taken, please choose another one.'
							errormsg.style.opacity = '1';
							var t = setInterval(function() {
								errormsg.style.opacity = errormsg.style.opacity - 0.1
							}, 200);
							setTimeout(function() {clearInterval(t);
								errormsg.style.opacity = '0'
							}, 2000)
						} else {
							okmsg.innerHTML = 'Registered successfully, now you can login.'
							okmsg.style.opacity = '1';
							var t = setInterval(function() {
								okmsg.style.opacity = okmsg.style.opacity - 0.1
							}, 200);
							setTimeout(function() {clearInterval(t);
								okmsg.style.opacity = '0'
							}, 1900)
						}
					}
				}
				xmlhttp.send(null);
			}

			//allows login by pressing return, instead of clicking on the login button
			function loginWithKey(event) {
				if(event.keyCode == 13) {
					console.log('login')
					return login();
				}
			}

			//sets the remember var to true or false depending on the checkbox
			function rememberData() {
				var checkbox = document.getElementById('rememberdata')
				if(checkbox.checked === true) {
					remember = true
					console.log('set remember to true')
				} else {
					remember = false;
					console.log('set remember to false')
				}
			}

			//sets a cookie for webble
			function setCookie(user, pw, exdays) {
				var exdate = new Date()
				exdate.setDate(exdate.getDate() + exdays);
				var c_value = escape(';username=' + user + ';password=' + pw + ';expires=' + exdate.toUTCString())
				document.cookie = 'webble_c' + '=' + c_value;
				console.log('cookie set')
			}

			//gets info about the user from the cookie
			function getCookieInfo(c_name) {
				if(!document.cookie) { return }
				console.log(unescape(document.cookie))
				var readable = unescape(document.cookie)
				var infos = readable.split(';')
				//console.log(infos)
				var user = infos[1].split('=')[1]
				var password = infos[2].split('=')[1]
				return [user, password]
			}

			//to login using the cookie
			function loginWithCookie() {
				var username = getCookieInfo()[0]
				var password = getCookieInfo()[1]
				var xmlhttp = new XMLHttpRequest();
				xmlhttp.open("GET", location.href +'user/?name=' + username + '&pw=' + password, true);
				xmlhttp.onload = function() {
					if(xmlhttp.readyState == 4) {
						var res = JSON.parse(xmlhttp.response);
						var id = res.id;
						var user = res.user;
						if(password === user.password) {
							var xmlhttp2 = new XMLHttpRequest()
							xmlhttp2.open('GET', location.href +'CodeBubble/?id=' + id)
							xmlhttp2.onload = function() {
								if(xmlhttp2.readyState == 4) {
									document.getElementById('dom').innerHTML = xmlhttp2.response;
									//get IDE page
									eval(document.getElementById('bootScript').innerHTML)//load libraries
									theUser = username;
									//set the user
									eval(document.getElementById('identify').innerHTML)			  // just to put the username on the page
								}
							}
							xmlhttp2.send();
						}
					}
				}
				xmlhttp.send(null)
			}
			$(document).ready(function(){	
				$('#presentation'
				).fadeIn(3000);
				});


		</script>
	</head>
	
	<!---------------------------------------------------------------------------------------------------------------------------->
	
	<body id='body' onkeyup='loginWithKey(event)' onbeforeunload = 'askViewToServer()'>
		<div id='userdata' >
			<div id="logincontainer">
				<input type="text" name="username" id="username"/ placeholder='Username'>
				<input type="password" name="password" id="password"/ placeholder='Password'>
				<input id='rememberdata' type='checkbox' value='Remember username/password' onchange='rememberData()'/>
				<span id="rememberdatatext">Remember <br> username/password</span>
			</div>
			<div id='loginbutton' onclick='login()'>
				Login
			</div>
		</div>
		<hr>
		<div id='mainblock'>
			<div id='okmsg'>
				Ok msg go here
			</div>
			<div id='errormsg'>
				Errors go here
			</div>
			<div id='presentation' style="display: none">
				<span id='idename'>Webble!</span></br>
				</br>
						Code Bubbles for the Web
			</div>
			<div id='registration'>
				<span id='new'>New to Webble! ? Register!</span>
				<input type="text" name="username" id="regusername"/ placeholder='Username'>
				</br>
				<input type="password" name="password" id="regpassword"/ placeholder='Password'>
				<div id='regbutton' onclick='register()'>
					Sign Up
				</div>
			</div>
		</div>
		<img id="logohome" style='position: absolute; left:40px;' src="../images/logo.png" alt="">
		<footer id='footer'>
			<img id='chromelogo' src='../stylesheets/images/chromelogo.png' alt=""/><span id='leftfoot'>Available only for Google Chrome</span><span id='rightfoot'>Webble! - Developed by: D'Avico - Gili - Mendola - Stampanoni</span>
		</footer>
	</body>
</html>